<?php
/**
 * 菜单管理
 * User: sam
 * Date: 13-6-22
 * Time: 下午3:59
 * To change this template use File | Settings | File Templates.
 */
class MenuAction extends OauthAction{
    function _initialize(){
        parent::_initialize();
        $this->_mode = D('Menu');
    }

    public function tree()
    {
        import('ORG.Util.Tree');
        $data = $this->_mode->fetch_tree_list();
        if(!empty($_REQUEST['checked'])){
            $_REQUEST['checked'] = base64_decode($_REQUEST['checked']);
            if(strpos($_REQUEST['checked'], ',') !== false)
                $checked = explode(',', $_REQUEST['checked']);
            else
                $checked = array($_REQUEST['checked']);
            foreach($data as $key => $row){
                if(in_array($row['id'], $checked))
                    $data[$key]['checked'] = true;
            }
        }
        $data = Tree::treeArray($data);
        if($_REQUEST['select']){
            $first[] = array('id' => 0, 'text' => '== 顶级菜单 ==', 'pid' => 0);
            $data = array_merge($first, $data);
        }
        die(json_encode($data));
    }

    /**
     * 获取子菜单
     * @param int $parent
     * @return mixed
     */
    public function children($parent = 0)
    {
        $menuList = $this->_mode->fetch_children($parent);
        die(json_encode($menuList));
    }

    public function _before_save()
    {
        $data = $this->_post();
        $data['menu_name'] or ajax_return(L('menu_name_lost'), 0);
        $data['class_name'] or ajax_return(L('class_name_lost'), 0);
        $condition = array();
        if(isset($data['menu_id'])){
            $data['menu_id'] or ajax_return(L('primary_lost'), 0);
            $condition['menu_id'] = array('neq', $data['menu_id']);
        }
        $condition['menu_name'] = $data['menu_name'];
        $condition['parent_id'] = $data['parent_id'];
        $total = $this->_mode->where($condition)->count();
        if($total > 0) ajax_return(L('menu_name_exists'), 0);
    }
}